﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Drawing2D;
using System.Reflection;

namespace DIProject.ReceptionGoods
{
    public partial class PartiesForm : Form
    {
        public PartiesForm()
        {
            InitializeComponent();
            lbNumDoc.DrawMode = DrawMode.OwnerDrawFixed;
            lbNumDoc.DrawItem += new DrawItemEventHandler(OnDrawListBoxItem);
        }

        private void PartiesForm_Load(object sender, EventArgs e)
        {
            DataSets.SettingsTableAdapters.ContragentsTableAdapter adapter = new DIProject.DataSets.SettingsTableAdapters.ContragentsTableAdapter();
            DataSets.Settings.ContragentsDataTable contrag = adapter.GetData();
            DataSets.Settings.ContragentsRow cr = contrag.NewContragentsRow();
            cr.Id = Int32.MinValue;
            cr.Name = "Выберите поставщика";
            contrag.Rows.InsertAt(cr, 0);
            cbSellers.ComboBox.ValueMember = "Id";
            cbSellers.ComboBox.DisplayMember = "Name";
            cbSellers.ComboBox.DataSource = contrag;
        }

        private void cbSellers_SelectedIndexChanged(object sender, EventArgs e)
        {
            Int32 tmp = (Int32)cbSellers.ComboBox.SelectedValue;
            if (tmp == Int32.MinValue)
                return;
            DataSets.waybillsDataTableAdapters.DocWithPartyTableAdapter adapter = new DIProject.DataSets.waybillsDataTableAdapters.DocWithPartyTableAdapter();
            DataSets.waybillsData.DocWithPartyDataTable dt = adapter.GetData(tmp);
            DataSets.waybillsData.DocWithPartyRow dr = dt.NewDocWithPartyRow();
            dr["DocNumber"] = "Выберите документ";
            dr["DocDate"] = DateTime.MinValue;
            dr["Id"] = Int32.MinValue;
            dt.Rows.InsertAt(dr, 0);
            lbNumDoc.DisplayMember = "DocNumber";
            lbNumDoc.ValueMember = "Id";
            lbNumDoc.DataSource = dt;
            this.IsChange = false;            
        }

        private void lbNumDoc_SelectedIndexChanged(object sender, EventArgs e)
        {
            Int32 tmp = (Int32)lbNumDoc.SelectedValue;
            if (tmp == Int32.MinValue)
                return;            
            DataSets.waybillsDataTableAdapters.PartiesTableAdapter adapter = new DIProject.DataSets.waybillsDataTableAdapters.PartiesTableAdapter();
            DataSets.waybillsData.PartiesDataTable dt = adapter.GetData(tmp);
            dgvParties.DataSource = dt;
            this.IsChange = false;
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            UpdateAll();
        }
        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            UnBlokedAll();
        }

        private void toolStripButton3_Click(object sender, EventArgs e)
        {
            BlokedAll();
        }
        #region изменение партий
        private bool _isChange;
        /// <summary>
        /// флаг показывающий, были ли изменения
        /// </summary>
        public bool IsChange
        {
            get { return _isChange; }
            set { _isChange = value; }
        }

        /// <summary>
        /// разблокируем все партии
        /// </summary>
        private void UnBlokedAll()
        {
            if (this.dgvParties.DataSource == null)
                return;
            object obj = this.dgvParties.DataSource;
            DataSets.waybillsData.PartiesDataTable parties = obj as DataSets.waybillsData.PartiesDataTable;
            if (parties != null)
            {
                foreach (DataSets.waybillsData.PartiesRow pr in parties.Rows)
                {
                    pr.Blocked = false;
                }
            }
            this.IsChange = true;
        }
        /// <summary>
        /// блокируем все партии
        /// </summary>
        private void BlokedAll()
        {
            if (this.dgvParties.DataSource == null)
                return;
            object obj = this.dgvParties.DataSource;
            DataSets.waybillsData.PartiesDataTable parties = obj as DataSets.waybillsData.PartiesDataTable;
            if (parties != null)
            {
                foreach (DataSets.waybillsData.PartiesRow pr in parties.Rows)
                {
                    pr.Blocked = true;
                }
            }
            this.IsChange = true;
        }
        /// <summary>
        /// обновляем данные в БД
        /// </summary>
        private void UpdateAll()
        {
            Int32 KarantinGroupId = Util.Karantin.KarantinGroupId;
            DataSets.waybillsDataTableAdapters.PartiesTableAdapter adapter = new DIProject.DataSets.waybillsDataTableAdapters.PartiesTableAdapter();
            if (this.dgvParties.DataSource == null)
                return;
            object obj = this.dgvParties.DataSource;
            DataSets.waybillsData.PartiesDataTable parties = obj as DataSets.waybillsData.PartiesDataTable;
            foreach (DataSets.waybillsData.PartiesRow pr in parties.Rows)
            {
                Int32 iTmp = Data.Goods.GetCatalog(pr.GoodsId);
               // if (iTmp == KarantinGroupId)
               //     continue;
                if (pr.RowState == DataRowState.Modified)
                {
                    pr.MW = FirstForm.Login;
                    pr.MD = DateTime.Now;
                    adapter.Update(pr);
                    Properties.Settings.Default["MoronConnectionString"] = "test";
                }
            }
            lbNumDoc_SelectedIndexChanged(lbNumDoc, EventArgs.Empty);
        }
        private void dgvParties_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            this.IsChange = true;
        }
        #endregion

        private void PartiesForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (this.IsChange)
            {
                DialogResult dr = MessageBox.Show("Данные были изменены. Сохранить изменения?", "Сохранение", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (dr == DialogResult.OK)
                {
                    this.UpdateAll();
                }
            }
        }

        private void pscToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (lbNumDoc.SelectedIndex < 0)
            {
                MessageBox.Show("Выберите накладную!");
                return;
            }
            Int32 docId = (Int32)lbNumDoc.SelectedValue;
            string s = Environment.CurrentDirectory + "\\Reports.dll";
            string ReportCoordinationPrices = System.Configuration.ConfigurationManager.AppSettings["ReportCoordinationPrices"];
            System.Runtime.Remoting.ObjectHandle f = Activator.CreateInstanceFrom(AppDomain.CurrentDomain, s, "Reports.ReportCoordinationPrices.PrintForm");
            //System.Runtime.Remoting.ObjectHandle f = Activator.CreateInstanceFrom(AppDomain.CurrentDomain, s, "Reports.GoodsTransfer.InputParamForm");
            object o = f.Unwrap();
            IntegrationInterface.IDIProjectForm i = o as IntegrationInterface.IDIProjectForm;
            if (i != null)
            {
                i.ConnectionString = Properties.Settings.Default.DIAptekaConnectionString;
                i.CommonProperty = ReportCoordinationPrices;
                i.Login = docId.ToString();
                System.Windows.Forms.Form ff = i.MailForm;
                ff.MdiParent = this.MdiParent;
                IntegrationInterface.IDIReport r = o as IntegrationInterface.IDIReport;
                r.InitReport(ReportCoordinationPrices);
                ff.Show();
            }
        }

        /// <summary>
        /// Ручная раскраска листбокса (метим партии с заблокированными позициями)
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void OnDrawListBoxItem(object sender, DrawItemEventArgs e)
        {
            if (e.Index < 0) return;
            ListBox listBox = sender as ListBox;
            if (listBox.Items.Count <= 0) return;
                        
            DataRowView drv = listBox.Items[e.Index] as DataRowView;
            DataSets.waybillsData.DocWithPartyRow dwprow = drv.Row as DataSets.waybillsData.DocWithPartyRow;

            if (e.Index == 0) // первая строка с текстом Выберите...
            {
                Color color1 = SystemColors.WindowText;
                e.Graphics.FillRectangle(Brushes.LightBlue, e.Bounds);
                e.Graphics.DrawString(dwprow.DocNumber, Font, new SolidBrush(color1), e.Bounds);
                return;
            }
            bool haveblock = false;
            //Рисуем выделенную строку
            if ((e.State & DrawItemState.Selected) != 0)
                e.Graphics.FillRectangle(SystemBrushes.Highlight, e.Bounds);
            else
            {
                if (dwprow.Nblocked > 0)
                {
                    e.Graphics.FillRectangle(Brushes.LightGreen, e.Bounds);
                    haveblock = true;
                }
                else
                    e.Graphics.FillRectangle(Brushes.White, e.Bounds);
            }

            string itemText = string.Empty;
            if (!dwprow.IsDocNumberNull())
            {
                itemText = dwprow.DocNumber;
                if (haveblock)
                    itemText += "(+)";
            }
            Color color = SystemColors.WindowText;
            //Рисуем строку
            e.Graphics.DrawString(itemText, Font, new SolidBrush(color), e.Bounds);
        }
    }
}